package poketrade;

import java.io.IOException;
import java.io.OutputStream;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.itextpdf.text.DocumentException;

import poketrade.entities.PendingOffer;
import poketrade.entities.User;
import poketrade.managers.DealManager;
import poketrade.utils.GenerationRecapitulatifAnnoncePDF;

/**
 * Servlet implementation class PDFGenerator
 */
public class PDFGenerator extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    @EJB
    private DealManager mng;
	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		long id = Long.parseLong(request.getParameter("id"));
		PendingOffer o = mng.getOffer(id);
		User userSession = (User) request.getSession().getAttribute("user");
		if (userSession.getId() != o.getBuyer().getId())
		{
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return;
		}
		
		GenerationRecapitulatifAnnoncePDF p = new GenerationRecapitulatifAnnoncePDF();
		// TODO C'est pas le prix en tenant compte des premium ou non.
		try {
			p.generate(userSession.getNom(), userSession.getPrenom(), userSession.getAdresse(), userSession.getVille(), o.getBasePrice(), o.getOffer().getCardIndex());
		} catch (DocumentException e) {
			e.printStackTrace();
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			return;
		}
		
		response.setContentLength(p.getContent().length);
		response.setContentType("application/pdf");
		OutputStream os = response.getOutputStream();
		os.write(p.getContent());
	}

	

}
